package br.com.caiocarrara.goodbuy.model.images;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.servlet.ServletContext;

import org.apache.tomcat.util.http.fileupload.IOUtils;

import br.com.caelum.vraptor.interceptor.multipart.UploadedFile;
import br.com.caelum.vraptor.ioc.Component;
import br.com.caiocarrara.goodbuy.model.Product;

@Component
public class Images {
	private File imagesFolder;

	public Images(ServletContext context) {
		String pathImages = context.getRealPath("WEB-INF/images");
		imagesFolder = new File(pathImages);
		imagesFolder.mkdir();
	}
	
	public void save(UploadedFile image, Product product) {
		File targetFile = new File(imagesFolder, product.getId() + ".image");
		
		try {
			FileOutputStream targetOutputStream = new FileOutputStream(targetFile);
			IOUtils.copyLarge(image.getFile(), targetOutputStream);
			image.getFile().close();
			targetOutputStream.close();
		} catch (IOException e) {
			throw new RuntimeException("Error copying image", e);
		}
	}

	public File load(Product product) {
		return new File(imagesFolder, product.getId() + ".image");
	}

}
